package com.graduate.cec.service;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.URLUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.graduate.cec.common.JsonPage;
import com.graduate.cec.common.ResponseCode;
import com.graduate.cec.exception.CecServiceException;
import com.graduate.cec.mapper.AdminMapper;
import com.graduate.cec.pojo.dto.AdminLoginDTO;
import com.graduate.cec.pojo.dto.AdminSimplePageDTO;
import com.graduate.cec.pojo.entity.Admin;
import com.graduate.cec.pojo.entity.AdminExample;
import com.graduate.cec.pojo.vo.AdminLoginVO;
import com.graduate.cec.pojo.vo.AdminSimpleVO;
import com.graduate.cec.pojo.vo.AdminVO;
import com.graduate.cec.security.JwtConst;
import io.jsonwebtoken.Header;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;

@Service
@Slf4j
public class AdminService{
    @Autowired
    AdminMapper adminMapper;

    @Value("${kbs.jwt.secret-key}")
    private String secretKey;

    String dirPath = null;
    //上传图片
    public String uploadPictures(MultipartFile picFile) throws Exception {
        String urlStr = URLUtil.getURL(FileUtil.file("picture")).toString();
        dirPath = urlStr.substring(urlStr.indexOf("cec"), urlStr.indexOf("target"));
        String prefix = urlStr.substring(6, urlStr.indexOf("cec"));
        dirPath += "picture/";
        dirPath = prefix + dirPath + "card";

        String fileName = picFile.getOriginalFilename();

        //得到后缀名 从最后一个.出现的位置截取到最后
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //得到唯一文件名 UUID.randomUUID()得到一个唯一标识符
        fileName = UUID.randomUUID() + suffix;
        log.info("fileName = " + fileName);
        //准备保存图片的文件夹路径
        File dirFile = new File(dirPath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        //得到文件的完整路径
        String filePath = dirPath + "/" + fileName;
        log.info("filePath = " + filePath);
        //把文件保存到此路径
        picFile.transferTo(new File(filePath));
        //"http://localhost:19090/picture/article/"
        return  "http://localhost:19090/picture/card/" + fileName;
    }

    public Long register(Admin admin) {
        if (adminMapper.selectLoginInfoByPhone(admin.getPhone()) == null) {
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            admin.setPassword(passwordEncoder.encode(admin.getPassword()));
            admin.setAvatar("https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png");

            admin.setPhone(admin.getPhone());
            admin.setIsEnable((byte) 0);

            int i = adminMapper.insertSelective(admin);
            log.info("注册的用户id:{}",admin.getId());
            if(i == 0){
                throw new CecServiceException(ResponseCode.INSERT_INFO_ERROR,"注册失败!");
            }else{
                return admin.getId();
            }

        }else{
            throw new CecServiceException(ResponseCode.INSERT_INFO_ERROR,"管理员已存在!");
        }
    }



    /****************        删       ******************************************************************/
    //删除上传的图片
    public void removePicture(String pictureName) {
        System.out.println(pictureName);
        String[] split = pictureName.split("/");
        pictureName = split[split.length - 1];
        System.out.println(pictureName);
        String filePath = dirPath + "/" + pictureName;
        System.out.println(filePath);
        new File(filePath).delete();
    }



    public AdminSimpleVO selectSimplePersonal(){
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String phone = (String) principal;
        log.info("selectSimplePersonal phone:{}",phone);
        return adminMapper.selectSimplePersonal(phone);
    }

    public void updateInfo(Admin admin){
        if(admin.getPassword() != "" && admin.getPassword() != null){
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            admin.setPassword(passwordEncoder.encode(admin.getPassword()));
        }


        AdminExample adminExample = new AdminExample();
        AdminExample.Criteria criteria = adminExample.createCriteria();
        criteria.andIdEqualTo(admin.getId());
        int i = adminMapper.updateByExampleSelective(admin, adminExample);
        if(i == 0){
            throw new CecServiceException(ResponseCode.UPDATE_INFO_ERROR,"更新失败!");
        }
    }

    public JsonPage<AdminVO> selectAllAdmin(AdminSimplePageDTO adminSimplePageDTO){
        PageHelper.startPage(adminSimplePageDTO.getPageNum(), adminSimplePageDTO.getPageSize());


        List<AdminVO> admins = adminMapper.selectByExample(adminSimplePageDTO);

        return JsonPage.restPage(new PageInfo<>(admins));

    }
}
